// pages/index/search/search.js
const app = getApp();

Page({

  /**
   * 页面的初始数据
   */
  data: {
    historyList:[],
    list:[],
    arrays:[],
    search:'',
    searchList:[],
  },

  
  onLoad: function (options) {
    let self=this,
        list = wx.getStorageSync("history"); 
        self.setData({
          list: list
        })
    app.util.ajax({ 
        url:'api/index/searchHistory'
      },res=>{
        
        self.setData({
          historyList: res.data.data,
        })
        
    })
    
  },
  clear(){
    wx.clearStorageSync("history");
    this.setData({
      list:'',
    })
  },
  submit(e){
   
    let self=this,
        search = e.detail.value.search,
        arrays=self.data.arrays;
       
    let array=wx.getStorageSync("history");
    

    if (search) {
      app.util.ajax({ 
        url:'api/index/search',
        data:{
          keyword:search
        }
      },function(res){
          console.log(res.data.data);
          self.setData({
            searchList: res.data.data
          })
          wx.navigateTo({
            url: './searchList/searchList'
          })
      })
     
      if (!array) {
        arrays.push(search)
        self.setData({
          arrays: arrays,
          search: ''
        })
        wx.setStorageSync("history", self.data.arrays);
      } else {
        if (array.length < 10) {
          array.unshift(search);
          self.setData({
            search: ''
          })
        } else {
          array.pop();
          array.unshift(search);
          self.setData({
            search: ''
          })
        }
        let list1 = self.uniq(array);

        wx.setStorageSync("history", list1);
      } 

     
    }
      
   
  },
  // 去重
  uniq(array){
    var temp = []; //一个新的临时数组
    for(var i = 0; i<array.length; i++){
        if (temp.indexOf(array[i]) == -1) {
          temp.push(array[i]);
        }
      }
      return temp;
  }

})